package com.example.ticketingserver.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.ticketingserver.dto.OrderDetails;
import com.example.ticketingserver.dto.R;
import com.example.ticketingserver.entity.*;
import com.example.ticketingserver.service.LineService;
import com.example.ticketingserver.service.OrdertextService;
import com.example.ticketingserver.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import static com.baomidou.mybatisplus.extension.toolkit.Db.getOne;
import static com.baomidou.mybatisplus.extension.toolkit.Db.save;

@CrossOrigin //开启不同源的访问，允许来自任何源的访问。
@Tag(name = "订单接口",description = "订单相关功能接口，包含：创建，删除。")
@RestController
public class OrderTextController {
    @Autowired
    private OrdertextService ordertextService;
    @Autowired
    private UserService userService;
    @Autowired
    private LineService lineService;

    @Operation(summary = "订单添加",description = "需要提供订单名称")
    @PostMapping("/order/reg")
    public R add(@Parameter(description = "订单") @RequestBody Ordertext ordertext){
//获取查询条件构造器
        QueryWrapper<Ordertext> query = Wrappers.query(Ordertext.class);
        query.eq("id",ordertext.getId());
        //执行查询
        Ordertext one = getOne(query);
        if(Objects.nonNull(one)){
            return R.fail().setMsg("订单号已存在");
        }
        if(save(ordertext)){
            return R.ok().setMsg("添加成功！").setData(ordertext);
        }
        return R.fail().setMsg("添加失败！");
    }
    @Operation(summary = "订单删除", description = "根据订单id删除记录，该操作为物理删除，请谨慎处理")
    @DeleteMapping("/order/del/{id}")
    public R del(@Parameter(description = "订单id") @PathVariable("id") Integer id){
        Ordertext ordertext = ordertextService.getById(id);
        if (Objects.isNull(ordertext)){
            return R.fail().setMsg("该订单不存在！");
        }
        return ordertextService.removeById(id) ? R.ok().setMsg("删除成功").setData(ordertext) : R.fail().setMsg("删除失败");
    }
    /**
     * 分页查询
     * @param page
     * @param limit
     * @return
     */
    @Operation(summary = "订单列表",description = "显示所有订单，含分页功能，需要提供当前页码（page），以及每页限制条数（limit）")
    @Parameters({
            @Parameter(name = "page",description = "当前页码",required = true),
            @Parameter(name = "limit",description = "每页的条数",required = true),
    })
    @GetMapping("/order/list")
    public R list(@RequestParam(defaultValue = "1") Integer page,@RequestParam(defaultValue = "5") Integer limit){
        List<OrderDetails> details = new ArrayList<>();
        //        执行分页查询
        List<Ordertext> list = ordertextService.list(new Page<Ordertext>(page, limit));
        list.forEach(m->{
//           获取订单id
            Integer uid = m.getUid();
            User user = userService.getById(uid);
//            获取车次id
            Integer lineid = m.getLineid();
            Line line = lineService.getById(lineid);

            OrderDetails md = new OrderDetails();
            md.setId(m.getId());

            md.setUsername(user.getUsername());
            md.setSex(user.getSex());
            if(line != null) {
                md.setLid(line.getId());
                md.setStartingstation(line.getStartingstation());
                md.setDestination(line.getDestination());
                md.setDate(line.getDate());
                md.setDeparturetime(line.getDeparturetime());
                md.setArrivaltime(line.getArrivaltime());
                md.setPrice(line.getPrice());
            }
            details.add(md);
        });
        long count = ordertextService.count();

        return R.ok().setData(details).setCount(count);
    }
    @Operation(summary = "查询所有订单",description = "所有订单")
    @GetMapping("/order/listAll")
    public R queryAll(){
        List<Ordertext> list = ordertextService.list();
        return R.ok().setMsg("查询成功").setData(list);
    }
    @Operation(summary = "订单修改", description = "根据id")
    @PutMapping("/order/update")
    public R modify(@Parameter(description = "收藏夹对象") Ordertext ordertext){

//        根据id修改管理员信息(务必传入管理员id)
        boolean b = ordertextService.updateById(ordertext);
        return b ? R.ok().setMsg("修改成功！").setData(ordertext) : R.fail().setMsg("修改失败！");
    }
}
